<?php

namespace App\Service\SiteLocation;

use App\Models\Kms\User\KmsUser;
use App\Models\Wanggui\CustomerDepartmentFollowUpRecordModel;
use App\Models\Wanggui\CustomerDepartmentKpPartyRecordModel;
use App\Models\Wanggui\CustomerDepartmentTaskModel;
use App\Service\BaseService;
use Carbon\Carbon;

class KpPartyService extends BaseService
{

    /**
     * 数据看板
     * @return array[]
     */
    public static function overview(): array
    {
        return [
            [
                'text'  => '甲方总数',
                'count' => CustomerDepartmentKpPartyRecordModel::query()->count(),
            ],
            [
                'text'  => '关联项目',
                'count' => count(array_unique(CustomerDepartmentFollowUpRecordModel::query()->where('kpPartyId', '>', 0)->pluck('taskId')->toArray())),
            ],
            [
                'text'  => '达成合作',
                'count' => CustomerDepartmentKpPartyRecordModel::query()->where('cooperate', CustomerDepartmentKpPartyRecordModel::COOPERATE_ON)->count(),
            ]
        ];
    }


    /**
     * 列表
     * @param int $pageNum
     * @param int $pageSize
     * @param int $provinceCode
     * @param int $cityCode
     * @param int $districtCode
     * @param string $companyType
     * @param string $company
     * @param string $userId
     * @param string $phone
     * @param string $wechatCode
     * @param string $wgName
     * @param int $rmsUserId
     * @param string $followUpStartTime
     * @param string $followUpEndTime
     * @param string $createdStartTime
     * @param string $createdEndTime
     * @return array
     */
    public static function list(int $pageNum, int $pageSize, int $provinceCode, int $cityCode, int $districtCode, string $companyType, string $company, string $userId, string $phone, string $wechatCode, string $wgName, int $rmsUserId, string $followUpStartTime, string $followUpEndTime, string $createdStartTime, string $createdEndTime): array
    {
        $paginator = CustomerDepartmentKpPartyRecordModel::query()
            ->when($provinceCode, function ($query) use ($provinceCode) {
                $query->where('provinceCode', $provinceCode);
            })
            ->when($cityCode, function ($query) use ($cityCode) {
                $query->where('cityCode', $cityCode);
            })
            ->when($districtCode, function ($query) use ($districtCode) {
                $query->where('districtCode', $districtCode);
            })
            ->when(mb_strlen($companyType), function ($query) use ($companyType) {
                $query->where('companyType', $companyType);
            })
            ->when(mb_strlen($company), function ($query) use ($company) {
                $query->where('company', 'like', "%{$company}%");
            })
            ->when(mb_strlen($userId), function ($query) use ($userId) {
                $query->where('createdByUid', $userId);
            })
            ->when(mb_strlen($phone), function ($query) use ($phone) {
                $query->where('phone', $phone);
            })
            ->when(mb_strlen($wechatCode), function ($query) use ($wechatCode) {
                $query->where('wechatCode', $wechatCode);
            })
            ->when(mb_strlen($wgName), function ($query) use ($wgName) {
                $query->whereRaw("id in (select kpPartyId from customer_department_follow_up_record where taskId in (select id from customer_department_task where wgName like '%{$wgName}%'))");
            })
            ->when(mb_strlen($createdStartTime) && mb_strlen($createdEndTime), function ($query) use ($createdStartTime, $createdEndTime) {
                $query->whereBetween("createdAt", [Carbon::createFromDate($createdStartTime)->timestamp, Carbon::createFromDate($createdEndTime)->endOfDay()->timestamp]);
            })
            ->when(mb_strlen($followUpStartTime) && mb_strlen($followUpEndTime), function ($query) use ($followUpStartTime, $followUpEndTime) {
                $query->whereBetween('followUpTime', [Carbon::createFromDate($followUpStartTime)->timestamp, Carbon::createFromDate($followUpEndTime)->endOfDay()->timestamp]);
            })
            ->orderByDesc('followUpTime')
            ->with(['followUpLastRel.taskRel'])
            ->paginate($pageSize, ['*'], 'pageNum', $pageNum);


        $userIds   = $paginator->pluck('createdByUid')->toArray();
        $userInfos = [];
        KmsUser::query()
            ->whereIn('rmsUserId', $userIds)
            ->get()
            ->each(function (KmsUser $kmsUser) use (&$userInfos) {
                if ($kmsUser->rmsUserId != 0) {
                    $userInfos[$kmsUser->rmsUserId] = $kmsUser->nickname . '(' . $kmsUser->name . ')';
                }
            });

        $list = $paginator->map(function ($item) use ($userInfos) {


            // 最新跟进时间
            $lastFollowUpTime  = '-';
            $relationWgNameArr = []; // 关联项目
            if (count($item->followUpLastRel)) {
                $lastFollowUpTime = $item->followUpLastRel->last()->createdAt->format('Y-m-d H:i:s');
                foreach ($item->followUpLastRel as $followUpRel) {
                    if (null != $followUpRel->taskRel) {
                        $relationWgNameArr[$followUpRel->taskRel->id] = $followUpRel->taskRel->wgName;
                    }
                }
            }

            return [
                'id'               => $item->id,
                'name'             => $item->name,
                'relationTask'     => implode(',', array_values($relationWgNameArr)),
                'company'          => $item->company,
                'prefixAddress'    => $item->prefixAddress,
                'companyType'      => $item->companyType,
                'companyTypeStr'   => CustomerDepartmentKpPartyRecordModel::COMPANY_TYPE_MAPPING[$item->companyType] ?? '-',
                'position'         => $item->position,
                'phone'            => $item->phone,
                'wechatCode'       => $item->wechatCode,
                'remark'           => $item->remark,
                'onTheJob'         => $item->onTheJob,
                'onTheJobStr'      => CustomerDepartmentKpPartyRecordModel::IS_ON_THE_JOB_MAPPING[$item->onTheJob] ?? '',
                'createdAt'        => $item->createdAt->toDateTimeString(),
                'createdUsername'  => $userInfos[$item->createdByUid] ?? '-',
                'lastFollowUpTime' => $lastFollowUpTime,
            ];
        });

        return [
            'count'    => $paginator->total(),
            'list'     => $list,
            'pageNum'  => $pageNum,
            'pageSize' => $pageSize,
        ];
    }

    /**
     * 关联项目列表
     * @param int $pageNum
     * @param int $pageSize
     * @param string $wgName
     * @return array
     */
    public static function relationProject(int $pageNum, int $pageSize, string $wgName): array
    {
        $paginator = CustomerDepartmentTaskModel::query()
            ->where('assignId', '>', 0)
            ->when(mb_strlen($wgName), function ($query) use ($wgName) {
                $query->where('wgName', 'like', "%{$wgName}%");
            })
            ->paginate($pageSize, ['*'], 'pageNum', $pageNum);

        $list = $paginator->map(function ($item) {
            return [
                'id'              => $item->id,
                'wgName'          => $item->wgName,
                'grade'           => $item->grade,
                'ranking'         => $item->ranking,
                'gradeStr'        => CustomerDepartmentTaskModel::GRADE_MAPPING[$item->grade] ?? '-',
                'prefixAddress'   => $item->prefixAddress,
                'settle'          => $item->settle,
                'settleStr'       => CustomerDepartmentTaskModel::SETTLE_STATUS_MAPPING[$item->settle] ?? '未入驻',
                'manageStatus'    => $item->manageStatus,
                'manageStatusStr' => CustomerDepartmentTaskModel::MANAGE_STATUS_MAPPING[$item->manageStatus] ?? '未指派',
                'projectPhase'    => $item->projectPhase,
                'projectPhaseStr' => CustomerDepartmentTaskModel::PROJECT_PHASE_MAPPING[$item->projectPhase] ?? '-',
            ];
        });

        return [
            'count'    => $paginator->total(),
            'list'     => $list,
            'pageNum'  => $pageNum,
            'pageSize' => $pageSize,
        ];
    }

}
